package com.asyf.provider.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.xa.DataSourceProxyXA;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * druid数据源配置
 */
@Configuration
public class DataSourceProxyConfig2 {

    @Bean("primary")
    @ConfigurationProperties(prefix = "spring.datasource.druid.primary")
    public DruidDataSource dataSourceMaster() {
        return new DruidDataSource();
    }

    @Bean("secondary")
    @ConfigurationProperties(prefix = "spring.datasource.druid.secondary")
    public DruidDataSource dataSourceStorage() {
        return new DruidDataSource();
    }

    //配置数据源代理，支持自动和手动两种配
    @Bean(name = "primaryProxy")
    public DataSource masterDataSourceProxy(@Qualifier("primary") DruidDataSource dataSource) {
//        return new DataSourceProxy(dataSource);

        //开启XA模式-只需要改这一个地方
        //注意：seata-spring-boot-starter 要和seata-server的版本号一致 1.4.2
        return new DataSourceProxyXA(dataSource);
    }

    @Bean(name = "secondaryProxy")
    public DataSource storageDataSourceProxy(@Qualifier("secondary") DruidDataSource dataSource) {
//         return new DataSourceProxy(dataSource);
        return new DataSourceProxyXA(dataSource);
    }

    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource(@Qualifier("primaryProxy") DataSource primaryProxy,
                                        @Qualifier("secondaryProxy") DataSource secondaryProxy) {

        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();

        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put(DataSourceKey.PRIMARY.name(), primaryProxy);
        dataSourceMap.put(DataSourceKey.SECONDARY.name(), secondaryProxy);

        dynamicRoutingDataSource.setDefaultTargetDataSource(primaryProxy);
        dynamicRoutingDataSource.setTargetDataSources(dataSourceMap);

        DynamicDataSourceContextHolder.getDataSourceKeys().addAll(dataSourceMap.keySet());
        return dynamicRoutingDataSource;
    }

    @Bean(name = "namedParameterJdbcTemplate")
    @Primary
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate(@Qualifier("dynamicDataSource") DataSource dataSource) {
        return new NamedParameterJdbcTemplate(dataSource);
    }

}